﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Daniel Vaughan. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2009-05-17 19:15:22Z</CreationDate>
</File>
*/
#endregion

using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Input;

using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Commands;

using DanielVaughan.Calcium.Modules.Output;
using DanielVaughan.IO;
using DanielVaughan.Services;
using DanielVaughan.Calcium.Services;
#if SILVERLIGHT
using DanielVaughan.Input;
#endif

namespace DanielVaughan.Calcium.TextEditor
{

	/// <summary>
	/// This module provides a basic text editor, for working with text files.
	/// </summary>
	public partial class TextEditorModule : ModuleBase
	{
#if SILVERLIGHT
		static readonly Logging.ILog Log = Logging.LogManager.GetLog(typeof(TextEditorModule));
#endif

		#region ShowViewCommand
		DelegateCommand<object> newTextFileCommand;
		public DelegateCommand<object> NewTextFileCommand
		{
			get
			{
				if (newTextFileCommand == null)
				{
					newTextFileCommand = new DelegateCommand<object>(OnCreateNewTextFile);
				}
				return newTextFileCommand;
			}
		}

		void OnCreateNewTextFile(object obj)
		{
			CreateNewTextFile();
		}
		#endregion

		#region OpenTextFileCommand
		DelegateCommand<object> openTextFileCommand;
		public DelegateCommand<object> OpenTextFileCommand
		{
			get
			{
				if (openTextFileCommand == null)
				{
					openTextFileCommand = new DelegateCommand<object>(OnOpenTextFileCommand);
				}
				return openTextFileCommand;
			}
		}

		void OnOpenTextFileCommand(object obj)
		{
			OpenTextFile();
		}
		#endregion

		const string outputCategory = "Text Editor";
		string fileFilter = "Text files (*.txt)|*.txt";

		int newFileCount;

		public TextEditorModule()
		{
			Initialized += OnInitialized;
		}

		void OnInitialized(object sender, EventArgs e)
		{
			var commandService = Dependency.Resolve<ICommandService>();

			CreateNewTextFile();
#if !SILVERLIGHT
			/* New Text File */
			commandService.AddCommandBinding(NewTextFileCommand, CreateNewTextFile, () => true, 
				new KeyGesture(Key.N, ModifierKeys.Control));

			/* Open Text File */
			commandService.AddCommandBinding(OpenTextFileCommand, OpenTextFile, () => true,
				new KeyGesture(Key.O, ModifierKeys.Control));

			/* TODO: Make localizable resource. */
			ShowView(MenuNames.FileNew, new MenuItem { Command = NewTextFileCommand, Header = "Text File" });
			ShowView(MenuNames.FileOpen, new MenuItem { Command = OpenTextFileCommand, Header = "Text File" });

			/* The following demonstrates how the application can be prevented from closing. */
			var eventAggregator = Dependency.Resolve<IEventAggregator>();
			eventAggregator.GetEvent<Calcium.Events.ApplicationExitEvent>().Subscribe(OnApplicationExit);
#endif
		}

		void OnApplicationExit(CancelableEventArgs<object> e)
		{
			//e.Cancel = true;
		}

		bool OpenTextFile()
		{
#if SILVERLIGHT
			throw new NotImplementedException();
#else
			Log.Info("Attempting to open a text file.");

			var fileService = Dependency.Resolve<IFileService>();

			string fileNameUsed = null;
			string textFromFile = null;

			FileOperationResult operationResult = fileService.Open(
				name =>
					{

						textFromFile = File.ReadAllText(name);

						fileNameUsed = name;

					}, FileErrorAction.InformOnly, fileFilter);

			if (operationResult == FileOperationResult.Successful)
			{
				var view = new TextEditorView();
				ShowView(RegionNames.Workspace, view, true);

				view.TextEditorViewModel.CreateOpened(fileNameUsed, textFromFile);

				/* Send an output message. */
				var eventAggregator = Dependency.Resolve<IEventAggregator>();
				var outputPostedEvent = eventAggregator.GetEvent<OutputPostedEvent>();
				outputPostedEvent.Publish(new OutputMessage
				                          	{
				                          		Category = outputCategory, 
												Message = fileNameUsed + " opened."
				                          	});
			}
#endif
			return true;
		}

		bool CreateNewTextFile()
		{
			var view = new TextEditorView();
			ShowView(RegionNames.Workspace, view, true);

			string newFileName = string.Format("Untitled{0}.txt", ++newFileCount);
			view.TextEditorViewModel.CreateNew(newFileName);
			var eventAggregator = Dependency.Resolve<IEventAggregator>();
			var outputPostedEvent = eventAggregator.GetEvent<OutputPostedEvent>();
			outputPostedEvent.Publish(new OutputMessage
			                          	{
											/* TODO: Make localizable resource. */
			                          		Category = outputCategory, 
											Message = newFileName + " created." 
			                          	});
			return true;
		}
	}
}
